package bhbt.servlet;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bhbt.model.Admin;
import bhbt.utils.ContextUtil;
import bhbt.utils.SysConst;






import java.io.IOException;
import java.net.URLDecoder;

public class EncodeUrlFilter implements Filter {
	public final static String encoding = "UTF-8";
    
    private FilterConfig config = null;
    private String encode = null;
     
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        this.encode = config.getInitParameter("encoding");
        if(this.encode == null) {
            this.encode = encoding;
        }
    }
 
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        // rquest & response
        request.setCharacterEncoding(this.encode);
        if (this.encode != null) {
        	
        	res.setCharacterEncoding(this.encode);
        }  
        // url
        String uri = request.getRequestURI();
        request.getQueryString();
        String ch = URLDecoder.decode(uri, encode);
      
        if(uri.equals(ch)) {
            
            HttpSession session=request.getSession();
        	Admin admin = (Admin)session.getAttribute(SysConst.MG);
        	if(admin==null){
        		
        		HttpServletResponse response=(HttpServletResponse)res;
        		response.sendRedirect(request.getContextPath()+"/loginAdmin.jsp");
        	}else {
    			
    			chain.doFilter(req, res);
    		}
            
            return;
        }
        ch = ch.substring(request.getContextPath().length());
        config.getServletContext().getRequestDispatcher(ch).forward(req, res);
        
        
        
    }    
 
    public void destroy() {
        config = null;
    }
}
